using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class ResourceReferenceFinder : EditorWindow
{
    private List<Object> referencingAssets = new List<Object>();
    private Vector2 scrollPosition;
 
    // [MenuItem("Assets/(搜索)Find References", true)]
    // private static bool ValidateSearchReference()
    // {
    //     // 只在选中了对象且不是文件夹时才显示菜单项
    //     return Selection.activeObject != null && !AssetDatabase.IsValidFolder(AssetDatabase.GetAssetPath(Selection.activeObject));
    // }
 
    [MenuItem("Assets/(搜索)Find References #e")]
    private static void SearchReference()
    {
        // 创建并打开资源引用查找窗口
                
        if (Selection.activeObject != null && !AssetDatabase.IsValidFolder(AssetDatabase.GetAssetPath(Selection.activeObject)))
        {
            GetWindow<ResourceReferenceFinder>("Resource Reference Finder").ReferenceFinder(Selection.activeObject);
        }
    }


 
    private void OnGUI()
    {
        // 显示搜索结果
        EditorGUILayout.LabelField("Search Results:");
        // 滚动视图开始
        scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
        EditorGUILayout.BeginVertical();
 
        // 显示搜索结果
        for (int i = 0; i < referencingAssets.Count; i++)
        {
            EditorGUILayout.ObjectField(referencingAssets[i], typeof(Object), true, GUILayout.Width(300));
        }
 
        EditorGUILayout.EndVertical();
        EditorGUILayout.EndScrollView();
        // 滚动视图结束
    }
 
    // 查找引用
    private void ReferenceFinder(Object targetResource)
    {
        referencingAssets.Clear();
 
        // 获取选择资源的 GUID
        string assetPath = AssetDatabase.GetAssetPath(targetResource);
        string assetGuid = AssetDatabase.AssetPathToGUID(assetPath);
 
        // 遍历项目中所有 Prefab 文件
        string[] guids1 = AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" });
        string[] guids2 = AssetDatabase.FindAssets("t:Scene", new[] { "Assets" });
        string[] guids = guids1.Concat(guids2).ToArray();

        int length = guids.Length;
        for (int i = 0; i < length; i++)
        {
            string filePath = AssetDatabase.GUIDToAssetPath(guids[i]);
            EditorUtility.DisplayCancelableProgressBar("Checking", filePath, (float)i / length);
 
            // 读取 Prefab 文件内容，检查是否包含选择资源的 GUID
            string content = File.ReadAllText(filePath);
            if (content.Contains(assetGuid))
            {
                // 如果包含，将该 Prefab 添加到结果列表中
                Object referencingAsset = AssetDatabase.LoadAssetAtPath(filePath, typeof(Object));
                referencingAssets.Add(referencingAsset);
            }
        }
 
        // 清除进度条
        EditorUtility.ClearProgressBar();
    }
}